package com.zq.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;

import java.util.Date;

public class TokenUtil {
    private static final String SIGN="123456";
    public static String createToken(Integer userId,String username,long expireTime){
        long currentTimeMillis = System.currentTimeMillis();
        return JWT.create().
                withSubject("user")
                .withAudience(String.valueOf(userId))//将user id保存到token里面,作为载荷
                .withClaim("account",username)
                .withClaim("createTime",new Date())
                .withIssuedAt(new Date(currentTimeMillis))
                .withExpiresAt(new Date(currentTimeMillis+ expireTime))
                .sign(Algorithm.HMAC256(SIGN));//以SIGN作为token的秘钥
    }

    public static StatusEnum verifyToken(String token){
        try {
            JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
            return StatusEnum.SUCCESS;
        }catch (TokenExpiredException e){//token过期
            return StatusEnum.EXPIRED;
        }catch (Exception e){//其他异常,校验失败
            return StatusEnum.FAILED;
        }
    }

    public static Integer getUserIdByToken(String token){
        return Integer.valueOf(JWT.decode(token).getAudience().get(0));
    }

    public static String getAccountByToken(String token){
        return JWT.decode(token).getClaim("account").asString();
    }
}

